package com.insurance.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.insurance.common.common.ResponseData;
import com.insurance.common.constant.ConstantFlag;
import com.insurance.common.dto.OrderDto;
import com.insurance.common.enums.CommonEnum;
import com.insurance.common.enums.DeleteFlagEnum;
import com.insurance.common.utils.JwtOperatorUtil;
import com.insurance.entity.OrderEntity;
import com.insurance.enums.OrderStateEnum;
import com.insurance.service.OrderService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author Style
 * @version 1.0
 * @date 2021/3/10
 **/
//@Api(tags = "订单服务")
@Slf4j
//@RestController
//@RequestMapping("/order")
public class OrderController {

    /**
     * 订单service
     */
    @Autowired
    private OrderService orderService;

    /**
     * 分页查询订单列表
     *
     * @param page 分页条件
     * @param userToken 用户凭证
     * @return
     */
    @ApiOperation(value = "分页查询订单列表")
    @PostMapping("/queryOrderPage")
    public ResponseData<Page<OrderDto>> queryOrderPage(Page page, @RequestHeader(value = "Authorization") String token, @RequestHeader String userToken){
        String userId = "";
        try {
            //校验用户凭证
            if(JwtOperatorUtil.isTokenExpired(userToken)){
                log.error("【查询订单列表失败, 用户凭证错误】");
                return ResponseData.error(CommonEnum.USER_TOKEN_ERROR);
            }
            //获取用户主键
            userId = JwtOperatorUtil.getUserId(userToken);
            if(StringUtils.isBlank(userId)){
                log.error("【查询订单列表失败, 用户为空】");
                return ResponseData.success(CommonEnum.USER_TOKEN_ERROR);
            }
            //分页查询订单
            Page<OrderDto> orderPageInfo = orderService.queryIOrderPage(page, userId, null);
            return ResponseData.success(orderPageInfo);
        } catch (Exception e) {
            log.error("【用户：{}, 查询订单列表失败, 系统异常：{}】", userId, e.getMessage());
            return ResponseData.error(CommonEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 通过订单Id查询订单详情
     *
     * @param orderId 订单主键
     * @return
     */
    @ApiOperation(value = "通过订单Id查询订单详情")
    @PostMapping("/getOrderDetail/{orderId}")
    public ResponseData<OrderDto> getOrderDetail(@PathVariable String orderId, @RequestHeader(value = "Authorization") String token){
        try {
            //通过主键查询订单
            OrderEntity order = orderService.getById(orderId);
            if(order == null){
                log.error("【订单Id：{}, 通过主键查询订单失败, 订单不存在】", orderId);
                return ResponseData.error(CommonEnum.QUERY_ERROR_NODATA);
            }
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(order, orderDto);
            return ResponseData.success(orderDto);
        } catch (Exception e) {
            log.error("【订单Id：{}, 通过主键查询订单失败, 系统异常：{}】", orderId, e.getMessage());
            return ResponseData.error(CommonEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 保存订单
     *
     * @param orderDto
     * @return
     */
    @ApiOperation(value = "保存订单")
    @PostMapping("/saveOrder")
    public ResponseData saveOrder(OrderDto orderDto, @RequestHeader(value = "Authorization") String token, @RequestHeader String userToken){
        OrderEntity orderEntity = new OrderEntity();
        BeanUtils.copyProperties(orderDto, orderEntity);
        String checkOrder = checkOrder(orderEntity);
        if(!ConstantFlag.TRUE_STR.equals(checkOrder)){
            return ResponseData.error(checkOrder);
        }
        String appId = JwtOperatorUtil.getAppId(token);
        String userId = JwtOperatorUtil.getUserId(userToken);
        String cardId = JwtOperatorUtil.getCardId(userToken);
        orderEntity.setCreateTime(new Date());
        orderEntity.setAppId(appId);
        orderEntity.setCardId(cardId);
        orderEntity.setCreatePersonId(userId);
        orderEntity.setDeleteFlag(String.valueOf(DeleteFlagEnum.UN_DELETE.getCode()));
        orderEntity.setOrderState(OrderStateEnum.NO_PAY.getCode());
        boolean flag = orderService.save(orderEntity);
        return flag ? ResponseData.success(String.valueOf(orderEntity.getOrderId())) : ResponseData.error(CommonEnum.SAVE_ERROR);
    }

    /**
     * 通过订单Id修改订单状态
     *
     * @param orderId 订单Id
     * @param state 状态
     * @return
     */
    @ApiOperation(value = "通过订单Id修改订单状态")
    @PostMapping("/changeOrderState/{orderId}")
    public ResponseData changeOrderState(@PathVariable String orderId, @RequestParam String state, @RequestHeader(value = "Authorization") String token){
        OrderEntity order = orderService.getById(orderId);
        if(order == null){
            log.error("【订单Id：{}, 通过主键查询订单失败, 订单不存在】", orderId);
            return ResponseData.error(CommonEnum.QUERY_ERROR_NODATA);
        }
        order.setOrderState(state);
        order.setUpdateTime(new Date());
        boolean flag = orderService.updateById(order);
        return flag ? ResponseData.success(CommonEnum.OPERATION_SUCCESS) : ResponseData.error(CommonEnum.OPERATION_ERROR);
    }

    public String checkOrder(OrderEntity orderEntity){
        if(orderEntity.getProductId() == null){
            return "产品id不能为空";
        }
        if(StringUtils.isBlank(orderEntity.getOrderState())){
            return "订单状态不能为空";
        }
        if(orderEntity.getProposalId() == null){
            return "投保单id不能为空";
        }
        return ConstantFlag.TRUE_STR;
    }

}
